package com.sl.ffmpeg_plugin

import androidx.annotation.NonNull;

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar

/** FfmpegPlugin */
public class FfmpegPlugin : FlutterPlugin, MethodCallHandler {
//    private lateinit var channel: MethodChannel

    var videoManager: VideoManager? = null

    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "ffmpeg_plugin")
        channel.setMethodCallHandler(this);
    }

    companion object {
        lateinit var channel: MethodChannel

        @JvmStatic
        fun registerWith(registrar: Registrar) {
            channel = MethodChannel(registrar.messenger(), "ffmpeg_plugin")
            channel.setMethodCallHandler(FfmpegPlugin())
        }
    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        when (call.method) {
            "dealWithSingleCommend" -> {
                videoManager = VideoManager()
                videoManager?.run {
                    setCommend(call.argument<String>("commend")!!)
                    executeCommend(channel)
                }
            }
            "dealWithCommends" -> {
                videoManager = VideoManager()
                videoManager?.run {
                    addCommend(call.argument<List<String>>("commend")!!)
                    executeCommend(channel)
                }
            }
            "getVideoInfo" -> {
                val data = VideoManager().getVideoInfo(call.argument<String>("videoPath")!!)
                result.success(mapOf("data" to mapOf(
                        "height" to data.height,
                        "width" to data.width,
                        "rotation" to data.rotation
                )))
            }
            "cancel" -> {
                videoManager?.cancel(channel)
            }
        }
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }
}
